﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Caliburn.Micro;
using System.Threading;
using Phone.Framework.Threads;

namespace Phone.Framework.CaliburnExtensions.Results
{
    public interface IActionResult : IResult
    {
        void Set();

        ActionExecutionContext Context { get; set; }
    }


    public class ActionResult : IActionResult
    {
        private Action<IActionResult> _action;

        private AutoResetEvent _autoResetEvent = new AutoResetEvent(false);

        public ActionResult(Action<IActionResult> action)
        {
            _action = action;
        }

        public ActionExecutionContext Context { get; set; }

        public void Execute(ActionExecutionContext context)
        {
            Context = context;
            _action(this);
            ThreadPool.QueueUserWorkItem((object obj) =>
            {
                _autoResetEvent.WaitOne();
                UIThread.Invoke(() =>
                {
                    Completed(this, new ResultCompletionEventArgs());
                });
            });
        }

        public void Set()
        {
            _autoResetEvent.Set();
        }

        public event EventHandler<ResultCompletionEventArgs> Completed;
    }
}
